package com.jie.langlangmall.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.jie.langlangmall.bo.AdminUserDetails;
import com.jie.langlangmall.common.constant.MessageConstant;
import com.jie.langlangmall.common.constant.StatusConstant;
import com.jie.langlangmall.common.exception.Asserts;
import com.jie.langlangmall.common.util.RequestUtil;
import com.jie.langlangmall.dao.UmsAdminRoleRelationDao;
import com.jie.langlangmall.dto.UmsAdminParam;
import com.jie.langlangmall.dto.UpdateAdminPasswordParam;
import com.jie.langlangmall.mapper.UmsAdminLoginLogMapper;
import com.jie.langlangmall.mapper.UmsAdminMapper;
import com.jie.langlangmall.mapper.UmsAdminRoleRelationMapper;
import com.jie.langlangmall.model.*;
import com.jie.langlangmall.security.util.JwtTokenUtil;
import com.jie.langlangmall.security.util.SpringUtil;
import com.jie.langlangmall.service.UmsAdminCacheService;
import com.jie.langlangmall.service.UmsAdminService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author Jie
 * @Date 2024/11/21 21:41
 * @Email 3217998214@qq.com
 */
@Service
@Slf4j
public class UmsAdminServiceImpl implements UmsAdminService {

    @Autowired
    private UmsAdminMapper adminMapper;
    @Autowired
    private UmsAdminRoleRelationDao adminRoleRelationDao;
    @Autowired
    private UmsAdminLoginLogMapper loginLogMapper;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private UmsAdminRoleRelationMapper adminRoleRelationMapper;

    @Override
    public UmsAdmin getAdminByUsername(String username) {
        // 先从缓存中获取
        UmsAdmin admin = getCacheService().getAdmin(username);
        if (admin != null) {
            return admin;
        }
        // 缓存中没有就从数据库中获取
        UmsAdminExample example = new UmsAdminExample();
        example.createCriteria().andUsernameEqualTo(username);
        List<UmsAdmin> adminList = adminMapper.selectByExample(example);
        if (adminList != null && !adminList.isEmpty()) {
            admin = adminList.get(0);
            // 加入缓存
            getCacheService().setAdmin(admin);
            return admin;
        }
        return null;
    }

    @Override
    public UserDetails loadUserByUsername(String username) {
        UmsAdmin admin = getAdminByUsername(username);
        if (admin != null) {
            List<UmsResource> resourceList = getResourceList(admin.getId());
            return new AdminUserDetails(admin, resourceList);
        }
        throw new UsernameNotFoundException("用户名或密码错误");
    }

    @Override
    public UmsAdminCacheService getCacheService() {
        return SpringUtil.getBean(UmsAdminCacheService.class);
    }

    @Override
    public List<UmsResource> getResourceList(Long adminId) {
        // 先从缓存中获取数据
        List<UmsResource> resourceList = getCacheService().getResourceList(adminId);
        if (CollUtil.isNotEmpty(resourceList)) {
            return resourceList;
        }
        // 从数据库中获取
        resourceList = adminRoleRelationDao.getResourceList(adminId);
        if (CollUtil.isNotEmpty(resourceList)) {
            // 放入缓存
            getCacheService().setResourceList(adminId, resourceList);
        }
        return resourceList;
    }

    /**
     * 登录返回token
     *
     * @param username
     * @param password
     * @return
     */
    @Override
    public String login(String username, String password) {
        String token = null;
        try {
            UserDetails userDetails = loadUserByUsername(username);
//            log.info("密码：{}", userDetails.getPassword());
            if (!passwordEncoder.matches(password, userDetails.getPassword())) {
                Asserts.fail(MessageConstant.PASSWORD_ERROR);
            }
            if (!userDetails.isEnabled()) {
                Asserts.fail(MessageConstant.ACCOUNT_DISABLED);
            }
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            // 设置登录用户
            SecurityContextHolder.getContext().setAuthentication(authentication);
            token = jwtTokenUtil.generateToken(userDetails);
            insertLoginLog(username);
        } catch (AuthenticationException e) {
            log.warn("登录异常:{}", e.getMessage());
        }
        return token;
    }

    /**
     * 管理员用户注册
     *
     * @param umsAdminParam
     * @return
     */
    @Override
    public UmsAdmin register(UmsAdminParam umsAdminParam) {
        UmsAdmin umsAdmin = new UmsAdmin();
        BeanUtils.copyProperties(umsAdminParam, umsAdmin);
        umsAdmin.setCreateTime(new Date());
        umsAdmin.setStatus(StatusConstant.ENABLE);

        // 是否用户名已经注册过了
        UmsAdminExample example = new UmsAdminExample();
        example.createCriteria().andUsernameEqualTo(umsAdmin.getUsername());
        List<UmsAdmin> adminList = adminMapper.selectByExample(example);
        if (CollUtil.isNotEmpty(adminList)) {
            Asserts.fail(MessageConstant.USERNAME_EXIST);
        }

        // 对密码进行加密操作
        String encodePassword = passwordEncoder.encode(umsAdmin.getPassword());
        umsAdmin.setPassword(encodePassword);
        adminMapper.insert(umsAdmin);
        return umsAdmin;
    }

    /**
     * 获取指定用户对应的角色
     *
     * @param adminId
     * @return
     */
    @Override
    public List<UmsRole> getRoleList(Long adminId) {
        // 直接从数据库中查询的，不是缓存中查询的
        return adminRoleRelationDao.getRoleList(adminId);
    }

    /**
     * 刷新token
     *
     * @param token
     * @return 返回旧的token
     */
    @Override
    public String refreshToken(String token) {
        return jwtTokenUtil.refreshHeadToken(token);
    }

    /**
     * 退出登录
     *
     * @param username
     */
    @Override
    public void logout(String username) {
        // 清空缓存中的用户数据
        UmsAdmin admin = getCacheService().getAdmin(username);
        // 清空用户基本信息
        getCacheService().delAdmin(admin.getId());
        // 清空资源缓存
        getCacheService().delResourceList(admin.getId());
    }

    /**
     * 根据id获取用户信息
     *
     * @param adminId
     * @return
     */
    @Override
    public UmsAdmin getItem(Long adminId) {
        return adminMapper.selectByPrimaryKey(adminId);
    }

    /**
     * 根据用户名或者昵称分页查询用户
     *
     * @param keyword
     * @param pageSize
     * @param pageNum
     * @return
     */
    @Override
    public List<UmsAdmin> list(String keyword, Integer pageSize, Integer pageNum) {
        PageHelper.startPage(pageNum, pageSize);
        UmsAdminExample example = new UmsAdminExample();
        UmsAdminExample.Criteria criteria = example.createCriteria();
        if (!StringUtils.isEmpty(keyword)) {
            // select * from ums_admin where username like %keyword% or nick_name like %keyword%
            criteria.andUsernameLike("%" + keyword + "%");
            example.or(example.createCriteria().andNickNameLike("%" + keyword + "%"));
        }
        return adminMapper.selectByExample(example);
    }

    /**
     * 修改指定用户的信息
     *
     * @param id
     * @param admin
     * @return
     */
    @Override
    public int update(Long id, UmsAdmin admin) {
        admin.setId(id);
        UmsAdmin rawAdmin = adminMapper.selectByPrimaryKey(id);
        if (rawAdmin.getPassword().equals(admin.getPassword())) {
            //与原加密密码相同的不需要修改
            admin.setPassword(null);
        } else {
            //与原加密密码不同的需要加密修改
            if (StrUtil.isEmpty(admin.getPassword())) {
                admin.setPassword(null);
            } else {
                admin.setPassword(passwordEncoder.encode(admin.getPassword()));
            }
        }
        int count = adminMapper.updateByPrimaryKeySelective(admin);
        // 更新缓存
        getCacheService().delAdmin(id);
        return count;
    }

    /**
     * 删除指定用户的缓存
     *
     * @param id
     * @return
     */
    @Override
    public int delete(Long id) {
        // TODO: 删除用户关联的其他表的信息
        // 删除数据库
        int count = adminMapper.deleteByPrimaryKey(id);
        // 删除缓存
        getCacheService().delAdmin(id);
        getCacheService().delResourceList(id);
        return count;
    }


    /**
     * 更新密码
     *
     * @param param
     * @return
     */
    @Override
    public int updatePassword(UpdateAdminPasswordParam param) {
        if (StrUtil.isEmpty(param.getUsername())
                || StrUtil.isEmpty(param.getOldPassword())
                || StrUtil.isEmpty(param.getNewPassword())) {
            // 参数不正确
            return StatusConstant.SUBMIT_PARAM_ERROR;
        }
        UmsAdminExample example = new UmsAdminExample();
        example.createCriteria().andUsernameEqualTo(param.getUsername());
        List<UmsAdmin> adminList = adminMapper.selectByExample(example);
        if (CollUtil.isEmpty(adminList)) {
            // 不存在该用户
            return StatusConstant.CANT_FIND_USER;
        }
        UmsAdmin umsAdmin = adminList.get(0);
        if (!passwordEncoder.matches(param.getOldPassword(), umsAdmin.getPassword())) {
            // 原密码不正确
            return StatusConstant.OLD_PASSWORD_ERROR;
        }
        // 更新数据库
        umsAdmin.setPassword(passwordEncoder.encode(param.getNewPassword()));
        adminMapper.updateByPrimaryKey(umsAdmin);
        // 更新缓存
        getCacheService().delAdmin(umsAdmin.getId());
        return StatusConstant.SUCCESS;
    }

    /**
     * 修改用户角色关系
     *
     * @param adminId
     * @param roleIds
     * @return
     */
    @Override
    public int updateRole(Long adminId, List<Long> roleIds) {
        int count = roleIds == null ? 0 : roleIds.size();
        // 先删除原来的关系 delete from ums_role_relation where admin_id = adminId
        UmsAdminRoleRelationExample adminRoleRelationExample = new UmsAdminRoleRelationExample();
        adminRoleRelationExample.createCriteria().andAdminIdEqualTo(adminId);
        adminRoleRelationMapper.deleteByExample(adminRoleRelationExample);
        // 建立新的关系
        if (!CollectionUtil.isEmpty(roleIds)) {
            List<UmsAdminRoleRelation> list = new ArrayList<>();
            for (Long roleId : roleIds) {
                UmsAdminRoleRelation roleRelation = new UmsAdminRoleRelation();
                roleRelation.setAdminId(adminId);
                roleRelation.setRoleId(roleId);
                list.add(roleRelation);
            }
            // 插入数据库
            adminRoleRelationDao.insertList(list);
        }
        // 更新缓存
        getCacheService().delResourceList(adminId);
        return StatusConstant.SUCCESS;
    }

    /**
     * 当前登录的管理员
     *
     * @return
     */
    @Override
    public UmsAdmin getCurrentAdmin() {
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        return getAdminByUsername(username);
    }

    /**
     * 添加登录记录
     *
     * @param username
     */
    private void insertLoginLog(String username) {
        UmsAdmin admin = getAdminByUsername(username);
        if (admin == null) return;
        UmsAdminLoginLog loginLog = new UmsAdminLoginLog();
        loginLog.setAdminId(admin.getId());
        loginLog.setCreateTime(new Date());
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = null;
        if (attributes != null) {
            request = attributes.getRequest();
        }
        if (request != null) {
            loginLog.setIp(RequestUtil.getRequestIp(request));
        }
        loginLogMapper.insert(loginLog);
    }

}
